package Classic150;

public class 在排序数组中查找元素的第一个和最后一个位置 {
    /*
        通过 +-0.5 二分查找找边界
     */
    public int[] searchRange(int[] nums, int target) {
        if (nums.length == 0) return new int[]{-1, -1};
        int start = binarySearch(nums, target - 0.5);
        int end = binarySearch(nums, target + 0.5) - 1;
        if (start < nums.length && nums[start] == target) return new int[]{start, end};
        return new int[]{-1, -1};
    }

    private int binarySearch(int[] nums, double target) {
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] < target) left = mid + 1;
            else right = mid - 1;
        }
        return left;
    }
}
